<template>
  <div class="column-manage">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-table
      v-if="refreshTable"
      :data="tableData"
      row-key="columnId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="columnName" label="栏目名称" align="center" />
      <el-table-column prop="cloumnType" label="栏目类型" align="center" />
      <el-table-column prop="sortOrder" label="排序" align="center" width="150" />
      <!-- 链接地址列 -->
      <el-table-column label="链接地址" align="center">
        <template #default="scope">
          <a
            :href="formatLink(scope.row.linkAddress)"
            target="_blank"

          >
            {{ scope.row.linkAddress }}
          </a>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="350" align="center">
        <template #default="scope">
          <el-button type="info" @click="handleEdit(scope.row)" plain size="mini">编辑</el-button>
          <el-button type="info" @click="handleAddChild(scope.row)" v-if="scope.row.cloumnType === '列表栏目' && !scope.row.parentId" size="mini">
            新增子栏目
          </el-button>
          <el-button size="mini" type="info"
            @click="handleVisible(scope.row, scope.row.visible === '1' ? '0' : '1')">
            {{ scope.row.visible === '1' ? '显示' : '隐藏' }}
          </el-button>
          <el-button type="info" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加/编辑栏目对话框 -->
    <el-dialog  :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="栏目类型" v-if="!form.columnId" prop="cloumnType">
          <el-select v-model="form.cloumnType" placeholder="请选择栏目类型">
            <el-option
              v-for="dict in dict.type.wa_dict_type"
              :key="dict.value"
              :label="dict.value"
            >
              {{dict.label}}
            </el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="栏目名称" prop="columnName">
          <el-input v-model="form.columnName" max-length="6" placeholder="请输入栏目名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" type="number" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="链接地址" prop="linkAddress" v-if="form.cloumnType === '跳转链接'">
          <el-input v-model="form.linkAddress" placeholder="请输入跳转链接" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listColumn,
  addColumn,
  updateColumn,
  delColumn,
  showColumn,
  hideColumn,
  childList
} from '@/api/publish/column'
import {listRole} from "@/api/system/role";

export default {
   dicts:['wa_dict_type'],
  data() {
    return {
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      loading:true,
      showSearch: true,
      deptList:[],
      deptOptions:[],
      tableData: [],
      dialogVisible: false,
      selectedIds: [], // 批量操作选中的ID
      form: {
        columnId: null,
        columnName: '',
        cloumnType: '列表栏目',
        sortOrder: 1,
        linkAddress: '',
        parentId: null,
        visible: '0' // 默认显示
      },

      // 表单验证规则
      rules: {
        columnName: [
          { required: true, message: '请输入栏目名称', trigger: 'blur' },
          { max: 6, message: '栏目名称最多6个字符', trigger: 'blur' }
        ],
        cloumnType: [
          { required: true, message: '请选择栏目类型', trigger: 'change' }
        ],
        linkAddress: [
          { required: true, message: '请输入链接地址', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadColumnList()
  },
  methods: {
    async loadColumnList() {

      try {
        const response = await listColumn(this.queryParams); // 注意：此处需修改后端接口，返回所有栏目（包括已隐藏的）
        // 处理树形结构（保留所有子栏目，无论是否隐藏）
        this.tableData = this.handleTree(response.rows, "columnId");
        // 确保子栏目结构完整
        this.ensureChildrenField(this.tableData);
        this.total = response.total || 0;
      } catch (error) {
        console.error('加载栏目列表失败', error);
        this.$message.error('加载栏目失败，请重试');
      }
    },

// 确保所有节点包含children字段
    ensureChildrenField(nodes) {
      nodes.forEach(node => {
        if (!node.children) node.children = [];
        this.ensureChildrenField(node.children);
      });
    },

    // 新增栏目
    handleAdd() {
      this.form = {
        columnId: null,
        columnName: '',
        cloumnType: '列表栏目',
        sortOrder: 1,
        linkAddress: '',
        parentId: null,
        visible: '0'
      }
      this.dialogVisible = true
    },

    // 编辑栏目
    handleEdit(row) {
      this.form = {...row}
      this.dialogVisible = true
    },

    // 新增子栏目
    handleAddChild(parentRow) {
      this.form = {
        columnId: null,
        parentId: parentRow.columnId,
        columnName: '',
        cloumnType: '列表栏目',
        sortOrder: 1,
        linkAddress: '',
        visible: '0'
      }
      this.dialogVisible = true
    },

    // 保存栏目
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.form.columnId) {
              await updateColumn(this.form)
              this.$message.success('修改成功')
            } else {
              if (this.form.parentId) {
                await addColumn(this.form)
                this.$message.success('新增子栏目成功')
              } else {
                await addColumn(this.form)
                this.$message.success('新增栏目成功')
              }
            }
            this.dialogVisible = false
            this.loadColumnList()
          } catch (error) {
            console.error('保存失败', error)
            this.$message.error('保存失败：' + (error.response?.data?.msg || error.message))
          }
        }
      })
    },
    // 删除栏目
    async handleDelete(row) {
      this.$confirm(`确定要删除栏目"${row.columnName}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await delColumn(row.columnId)
          this.$message.success('删除成功')
          this.loadColumnList()
        } catch (error) {
          console.error('删除失败', error)
          this.$message.error('删除失败：' + (error.response?.data?.msg || error.message))
        }
      })
    },

    //递归检查所有子栏目是否已经隐藏
    checkAllChildrenHidden(column){
      if (column.children && column.children.length > 0) {
        for (const child of column.children) {
          // 子栏目未隐藏（visible=0），直接返回false
          if (child.visible === '0') {
            return false;
          }
          // 递归检查子栏目的子栏目
          if (!this.checkAllChildrenHidden(child)) {
            return false;
          }
        }
      }
      // 所有子栏目均已隐藏
      return true;
    },

    // 显示/隐藏栏目
    async handleVisible(row) {
      const currentVisible = row.visible;
      const targetVisible = currentVisible === '1'?'0':'1';
      const actionText = targetVisible ==='0'?'显示':'隐藏';
      if (targetVisible === '1' && (row.parentId === null || row.parentId === 0)) {
        // 检查所有子栏目是否已隐藏
        const allChildrenHidden = this.checkAllChildrenHidden(row);
        if (!allChildrenHidden) {
          this.$message.warning('存在未隐藏的子栏目，请先隐藏所有子栏目后再隐藏一级栏目');
          return;
        }
      }      try {
        if (targetVisible === '0') {
          await showColumn(row.columnId);
        } else {
          await hideColumn(row.columnId);
        }
        this.$message.success(`${actionText}成功`);
        this.loadColumnList();//重新加载列表
      } catch (error) {
        console.error('操作失败', error);
        this.$message.error(`${actionText}失败:${error.response?.data?.msg || error.message}`);
      }
    },
    // 格式化链接地址
    formatLink(link) {
      if (link && !link.startsWith('http://') && !link.startsWith('https://')) {
        return `http://${link}`
      }
      return link
    }
  }
}
</script>

<style scoped lang="scss">
.column-manage {
  padding: 20px;
}
::v-deep .el-dialog__body {
  padding: 20px;
}
::v-deep .el-form-item {
  margin-bottom: 15px;
}
</style>
